﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WorldBankBBS.Translators
{
    public static class Paginator
    {
        public static List<byte[]> Paginate(this byte[] sourceText, int position, int length, int lines, string encoding)
        {
            var result = new List<byte[]>();
            var current = new List<byte>();
            var last = 0;
            var lineCount = 0;

            for (int i = 0; i < length; ++i)
            {
                var b = sourceText[position + i];
                if (b == 0) break;

                if (encoding != "PETSCII")
                {
                    current.Add(b);
                    if ((b == 13 && last == 10) || (b == 10 && last == 13))
                    {
                        ++lineCount;

                        if (lineCount == lines)
                        {
                            result.Add(current.ToArray());
                            current = new List<byte>();
                            lineCount = 0;
                        }
                    }
                }
                else
                {
                    current.Add(b);
                    if (b == 13)
                    {
                        ++lineCount;

                        if (lineCount == lines)
                        {
                            result.Add(current.ToArray());
                            current = new List<byte>();
                            lineCount = 0;
                        }
                    }
                }

                last = b;
            }

            result.Add(current.ToArray());
            
            return result;
        }
    }
}
